<template>
  <div class="home-module">
    <template v-for="(coat, index) in templateList">
      <!-- banner START -->
      <Banner v-if="coat.key == 'banner'" :datas="coat" :key="index" :module-index="index"></Banner>
      <!-- banner END -->

      <!-- 广告位 START -->
      <Advert v-if="coat.key == 'advert'" :datas="coat" :key="index"></Advert>
      <!-- 广告位 END -->

      <!-- 课程 START -->
      <Course
        v-if="coat.key == 'course' || coat.key == 'intentCourse'"
        :datas="coat"
        :key="index"
        :module-index="index"
        @click="openIntentionDialog"
      ></Course>
      <!-- 课程 END -->

      <!-- 讲师 START -->
      <Teacher
        v-else-if="coat.key == 'teacher'"
        :datas="coat"
        :key="index"
        :module-index="index"
      ></Teacher>
      <!-- 讲师 END -->

      <!-- 资讯 START -->
      <Topic
        v-else-if="coat.key == 'topic'"
        :datas="coat"
        :key="index"
        :module-index="index"
      ></Topic>
      <!-- 资讯 END -->

      <!-- 分类课程 START -->
      <Featured
        v-else-if="coat.key == 'featured'"
        :datas="coat"
        :key="index"
        :module-index="index"
        :min-index="getFeaturedMinIndex()"
      ></Featured>
      <!-- 分类课程 END -->
    </template>

    <!-- 修改意向课程窗口 -->
    <intention
      v-if="intentionVisible"
      :visible.sync="intentionVisible"
      @submit="handleIntentionSubmit"
    ></intention>
  </div>
</template>
<script>
import Banner from './components/banner'
import Advert from './components/advert'
import Course from './components/course'
import Featured from './components/featured'
import Topic from './components/topic'
import Teacher from './components/teacher'
import Intention from './components/intention.vue'
export default {
  components: {
    Banner,
    Advert,
    Course,
    Featured,
    Topic,
    Teacher,
    Intention
  },
  data() {
    return {
      templateList: [],
      intentionVisible: false
    }
  },
  computed: {
    getFeaturedMinIndex() {
      return _ => {
        const index = this.templateList.findIndex(element => element.key == 'featured')
        return index
      }
    }
  },
  created() {
    this.getTemplateData()
  },
  methods: {
    getTemplateData() {
      this.$api.getHomeTemplate(res => {
        const { data } = res
        this.templateList = data
      })
    },
    // 打开弹窗选择意向课程
    openIntentionDialog() {
      this.intentionVisible = true
    },
    // 提交选择的意向课程
    handleIntentionSubmit(val) {
      this.intentionVisible = false
      this.$api.updateCourseFavorite(
        {
          category: val
        },
        res => {
          this.$message.success(res.msg)
          this.getTemplateData()
        }
      )
    }
  }
}
</script>
